<script lang="ts" setup>
import { ElLoading } from 'element-plus'
import LoginFormTitle from './LoginFormTitle.vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useIcon } from '@/hooks/web/useIcon'

import * as authUtil from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'

defineOptions({ name: 'LoginForm' })

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconLock = useIcon({ icon: 'ep:lock' })
const formLogin = ref()
const { validForm } = useFormValid(formLogin)
const { getLoginState } = useLoginState()
const { currentRoute, push } = useRouter()
const permissionStore = usePermissionStore()
const redirect = ref<string>('')
const loginLoading = ref(false)
const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
const userStore = useUserStore()

const rules = {
  username: [{ required: true, message: '请输入登录名', trigger: 'blur' },{min:3,message:'登录名至少3位',trigger: 'blur' },{max:50,message:'登录名最多50位',trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const loginFormRef = ref()

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

const LoginRules = {
  tenantName: [required],
  username: [required],
  password: [required]
}
const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE,
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  loginForm: {
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    username: import.meta.env.VITE_APP_DEFAULT_LOGIN_USERNAME || '',
    password: import.meta.env.VITE_APP_DEFAULT_LOGIN_PASSWORD || '',
    captchaVerification: '',
    rememberMe: true // 默认记录我。如果不需要，可手动修改
  }
})

const socialList = [
  { icon: 'ant-design:wechat-filled', type: 30 },
  { icon: 'ant-design:dingtalk-circle-filled', type: 20 },
  { icon: 'ant-design:github-filled', type: 0 },
  { icon: 'ant-design:alipay-circle-filled', type: 0 }
]

// 获取验证码
const getCode = async () => {
  console.info('getCode')
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await handleLogin({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}
// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
    authUtil.setTenantId(res)
  }
}
// 记住我
const getLoginFormCache = () => {
  const loginForm = authUtil.getLoginForm()
  if (loginForm) {
    loginData.loginForm = {
      ...loginData.loginForm,
      username: loginForm.username ? loginForm.username : loginData.loginForm.username,
      password: loginForm.password ? loginForm.password : loginData.loginForm.password,
      rememberMe: loginForm.rememberMe,
      tenantName: loginForm.tenantName ? loginForm.tenantName : loginData.loginForm.tenantName
    }
  }
}
// 根据域名，获得租户信息
const getTenantByWebsite = async () => {
  const website = location.host
  const res = await LoginApi.getTenantByWebsite(website)
  if (res) {
    loginData.loginForm.tenantName = res.name
    authUtil.setTenantId(res.id)
  }
}

const route = useRoute()

  const id =  route.query.id
const loading = ref() // ElLoading.service 返回的实例
// 登录
const handleLogin = async (params: any) => {

if(!loginFormRef.value) return 
await loginFormRef.value.validate(async (valid: boolean) => {
  if (valid) {


  loginLoading.value = true
  try {
    await getTenantId()

    const loginDataLoginForm = { ...loginData.loginForm }
    loginDataLoginForm.captchaVerification = params.captchaVerification
    loginDataLoginForm.password = btoa(loginDataLoginForm.password.trim())
    loginDataLoginForm.username = loginDataLoginForm.username.trim()
    const res = await LoginApi.login(loginDataLoginForm)
    if (!res) {
      return
    }
    loading.value = ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (loginDataLoginForm.rememberMe) {
      authUtil.setLoginForm(loginDataLoginForm)
    } else {
      authUtil.removeLoginForm()
    }
    authUtil.setToken(res)
    if (!redirect.value) {
      redirect.value = '/'
    }
    // 判断是否为SSO登录
    if (redirect.value.indexOf('sso') !== -1) {
      window.location.href = window.location.href.replace('/login?redirect=', '')
    } else {
      // 获取用户信息和权限
      await userStore.setUserInfoAction()
      // 生成路由
      await permissionStore.generateRoutes()
      // 跳转到模块首页
      await push({ path: '/moduleHome' ,query:{id:id}
      })
    }
  } finally {
    loginLoading.value = false
    loading.value?.close()
  }
}
})


}

// 社交登录
const doSocialLogin = async (type: number) => {
  if (type === 0) {
    message.error('此方式未配置')
  } else {
    loginLoading.value = true
    if (loginData.tenantEnable === 'true') {
      // 尝试先通过 tenantName 获取租户
      await getTenantId()
      // 如果获取不到，则需要弹出提示，进行处理
      if (!authUtil.getTenantId()) {
        try {
          const data = await message.prompt('请输入租户名称', t('common.reminder'))
          if (data?.action !== 'confirm') throw 'cancel'
          const res = await LoginApi.getTenantIdByName(data.value)
          authUtil.setTenantId(res)
        } catch (error) {
          if (error === 'cancel') return
        } finally {
          loginLoading.value = false
        }
      }
    }
    // 计算 redirectUri
    // tricky: type、redirect需要先encode一次，否则钉钉回调会丢失。
    // 配合 Login/SocialLogin.vue#getUrlValue() 使用
    const redirectUri =
      location.origin +
      '/social-login?' +
      encodeURIComponent(`type=${type}&redirect=${redirect.value || '/'}`)

    // 进行跳转
    window.location.href = await LoginApi.socialAuthRedirect(type, encodeURIComponent(redirectUri))
  }
}
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
onMounted(() => {
  getLoginFormCache()
  getTenantByWebsite()
})
</script>

<template>
 <div class="mobile-login-container">
    <div class="mobile-title-container">
      <div class="mobile-title-text">
        <p class="mobile-title-text-title">质量检验信息服务平台</p>
        <p class="text-xl">Quality Inspection Information Service Platform</p>
      </div>
    </div>

    <!-- 登录表单 -->
    <div class="mobile-login-form">
      <div class="mobile-login-form-container">
        <el-form  :model="loginData.loginForm" ref="loginFormRef" :rules="rules" class="login-form">
          <el-form-item  prop="username">
            <p>登录名</p>
            <el-input v-model="loginData.loginForm.username" placeholder="请输入登录名" />
          </el-form-item>
          <el-form-item  prop="password">
              <p>密码</p>
            <el-input type="password" v-model="loginData.loginForm.password" placeholder="请输入密码" />

            </el-form-item>

       
              <el-button class="w-full" type="primary" round size="large" @click="getCode">登录</el-button>
          </el-form>
          <div class="mobile-form-item  mobile-login-btn">
        
        </div>
        <!-- <div class="mobile-form-item">
          <p>登录名</p>
          <el-input v-model="loginData.loginForm.username" placeholder="请输入登录名" />
        </div>
        <div class="mobile-form-item">
          <p>密码</p>
          <el-input type="password" v-model="loginData.loginForm.password" placeholder="请输入密码" />
        </div>

        <div class="mobile-form-item  mobile-login-btn">
          <el-button type="primary" round size="large" @click="getCode">登录</el-button>
        </div> -->
      </div>
    </div>
 </div>
</template>

<style lang="scss" scoped>

.mobile-login-container{
  height: 100vh;
  background-color: #eee;
  
  .mobile-title-container{
    position: relative;
    width: 100%;
    height: 399px;
    padding: 20px;
    background-color: blue;
    background-image: url('@/assets/imgs/login/mobileLogin.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    

    .mobile-title-text{
      width: 100%;
      color: #fff;
    }
  }
}

.el-input {
  .el-input__wrapper {
    box-shadow: none !important;
  }
}

.mobile-login-form{
  position: absolute;
  top: 25%;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: transparent;

  &::before{
    position: absolute;
    left: 50px;
    width: 20px;
    height: 20px;
    background-color: #fff;
    content:'';
    transform: rotate(45deg);
  }

  .mobile-login-form-container{
    width: 100%;
    height: 100%;
    padding: 20px;
    background-color: #fff;
    border-radius: 10px;


    .mobile-form-item{
      margin-bottom: 20px;

      p{
        margin-bottom: 10px;
        font-size: 14px;
        color: #333;
      }

      .mobile-form-item-input{
        width: 100%;
        height: 40px;
        padding: 0 10px;
        font-size: 14px;
        border: 1px solid #ccc;
        border-radius: 4px;
      }
    }

    .mobile-login-btn{
      display: flex;
      width: 100%;
      margin-top: 100px;
      border-radius: 4px;
      justify-content: center ;
      align-items: center;

      button{
        width: 100%;
        height: 40px;
        font-size: 16px;
        color: #fff;
      }
    }
  }
}


.mobile-title-text-title{
  font-size: 22px;
  font-weight: bold;
}


</style>